package org.example.demo1.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.example.demo1.Entity.User;

import java.io.IOException;


import java.io.IOException;

public class ServletFilter implements Filter {

    private static final Logger logger = LogManager.getLogger(ServletFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        String path = httpRequest.getRequestURI();

        // 获取关键信息（即使未登录也记录）
        String ip = httpRequest.getRemoteAddr();

        // 从会话中获取用户信息
        String username = "anonymous";
        HttpSession session = httpRequest.getSession(false);
        if (session != null && session.getAttribute("user") != null) {
            User user = (User) session.getAttribute("user");
            username = user.getUsername();
        }

        String method = httpRequest.getMethod();    // GET/POST/PUT/DELETE

        try {
            // 存储到 Log4j2 的 ThreadContext（用于日志模板）
            ThreadContext.put("ip", ip);
            ThreadContext.put("user", username);
            ThreadContext.put("method", method);
            ThreadContext.put("path", path);

            // 记录日志（实际内容由 log4j2.xml 的 Pattern 决定）
            logger.info("Request Received");

            // 继续处理请求
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            // 清除 ThreadContext（防止内存泄漏）
            ThreadContext.clearAll();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
